<?php include '../yubiphpbase/appinclude.php';
include '../yubiphpbase/yubi_lib.php';
include 'head.htm';

$otp = getHttpVal('otp','');
$email = getHttpVal('email', '');

if (strlen($email) > 0) {
  if (validEmail($email)) { // Serve the api key request

    if (strlen($otp) < 10 || strlen(($err = verifyYubikeyOtp($otp))) > 0) {
    	if (strlen($otp) < 10) {
        	$err = 'Invalid OTP';
    	}
    	$_SESSION['alert'] = CLICK2LOGIN . ' - '.$err;
  	} else { // OTP verified
		$devid = substr($otp, 0, 12);
		$a = getKeyInfo($devid);
		$keyid = $a['keyid'];
		if (getClientByEmail($email) > 0 || $a['client'] > 1) {
			$_SESSION['alert'] = 'The account is already set up for you! '.
				'Retrieve your API key from <a href=index.php>Yubikey Management Service</a>.';
		} else {
  			$apikey = genAPIKey();
  			$app = getHttpVal('app', '');
  			$client = addClient($email, $apikey, 3, 
			$app.' - web req by '.$email.' from '.
  			$_SERVER['REMOTE_ADDR']);
  			if ($client < 1) {
  			  $_SESSION['alert'] = 'Failed to add a new client! '.$contactAdm;
  			} else {
  				updClientOfKey($keyid, $client);
  			}
		}
  	}
  } else {
  	$_SESSION['alert'] = 'The email "'. $email .'" is invalid!';
  }
}
?>

<html>
  <head>
    <title>Yubico - Get API Key</title>
  </head>

  <body onLoad="document.getapikey.app.focus();">
    <img src=images/trust_the_net.jpg >
<br><br>
    
    <h1>Yubico - Get API Key for Signing & Verifying OTP Validation 
    Requests</h1>
    
    <?php if (isset($client) && isset($apikey)) { ?>

    <p>Congratulations!  Please find below your client identity and
      client API key.

    <p><table border=1>
	<tr><td>Id:</td><td><?php print $client; ?></td></tr>
	<tr><td>API Key:</td><td><?php print $apikey; ?></td></tr>
      </table>

    <p>For more information on how to use this, see the <a href=http://yubico.com>
    	Developers web pages</a>.

    <?php } else { ?>

    <p>Here you can generate a shared symmetric key for use with the
      Yubico Web Services.  You need to authenticate yourself using a
      Yubikey One-Time Password and provide your e-mail address as a
      reference.

    <p><hr>
<?php showAlert(getAlert()); ?>

    <p><form name="getapikey" method=POST action=getapi.php autocomplete="off">
    <table>	  
 	  <tr><td>A brief description of your<br>application of Yubikey:</td>
	    <td><input type="text" name="app" maxlength=120 size=90></td></tr>	   	    
	  
	  <tr><td>E-mail address:</td>
	    <td><input type="text" name="email" maxlength=50 size=60></td></tr>
	  
	  <tr><td>Your Yubikey OTP:</td>
	    <td><input type="password" name="otp" maxlength=100 size=60></td></tr>	  
	  <tr><td colspan="2">
	  	<br><br>
	      <input class=buttonLinkO type="submit" value="Generate API Key"></td></tr>
	</table>
    </form>

    <?php } ?>

  </body>
</html>
